package com.jeecms.wicool.action.user;

import static com.jeecms.common.page.SimplePage.cpn;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.entity.user.Address;
import com.jeecms.wicool.entity.user.CheckCode;
import com.jeecms.wicool.entity.user.UserAccount;
import com.jeecms.wicool.entity.user.UserInfo;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.car.CarAdviserMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.manager.user.UserAccountMng;
import com.jeecms.wicool.manager.user.UserInfoMng;
import com.jeecms.wicool.manager.util.DictionaryMng;

/**
 * 会员Action
 */
@Controller
public class UserInfoAct {
	private static final Logger log = LoggerFactory.getLogger(UserInfoAct.class);

	@SuppressWarnings("unchecked")
	@RequestMapping("/user/v_list.do")
	public String list(Integer shopId,String name,String mobile,Short status,Integer carAdviserId,Date q_createTime_start,Date q_createTime_end,
			Integer pageNo,HttpServletRequest request, ModelMap model) {
		if (carAdviserId != null && carAdviserId.intValue() == 0) {
			carAdviserId = null;
		}
		Pagination pagination = manager.getPage(shopId,mobile,name,status,carAdviserId,q_createTime_start,
				q_createTime_end,cpn(pageNo),CookieUtils.getPageSize(request),CmsUtils.getUser(request));
		List<UserInfo> listUserInfo = (List<UserInfo>) pagination.getList();
		List<Dictionary2> listDic=DicMng.getList("user_status");
		Map<String,String> map = new HashMap<String,String>();
		 for(Dictionary2 d : listDic){
			 map.put(d.getDicCode().toString(), d.getDicName());
		 }
		 for(UserInfo p : listUserInfo){
			 if(map.containsKey(p.getStatus().toString())){
				 p.setStatusName(map.get(p.getStatus().toString()));
			 }
		 }
		 List<ShopInfo> shopList = shopInfoMng.getAll(CmsUtils.getUser(request));
		 List<UserInfo> carAdvisers = manager.getAll(CmsUtils.getUser(request));
		 UserInfo temp = new UserInfo();
		 temp.setId(0);
		 temp.setName("请选择");
		 carAdvisers.add(0, temp);
		 model.addAttribute("carAdvisers",carAdvisers);
		model.addAttribute("pagination", pagination);
		
		model.addAttribute("shopList",shopList);
		model.addAttribute("shopId",shopId);
		model.addAttribute("name",name);
		model.addAttribute("status",status);
		model.addAttribute("carAdviserId",carAdviserId);
		model.addAttribute("q_createTime_start",q_createTime_start);
		model.addAttribute("q_createTime_end",q_createTime_end);
		return "user/list_user";
	}
	
	@RequestMapping("/user/v_listAddress.do")
	public String listAddress(String userName,Integer shopId,String consigneeName,Integer pageNo,HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPageAddress(userName, shopId, consigneeName, cpn(pageNo),
				CookieUtils.getPageSize(request));
		List<ShopInfo> shopList = shopInfoMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		
		model.addAttribute("shopList",shopList);
		model.addAttribute("shopId",shopId);
		model.addAttribute("userName",userName);
		model.addAttribute("consigneeName",consigneeName);
		return "user/list_address";
	}
	@RequestMapping("/user/v_toEditUser.do")
	public String toEditUser(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("user_id",id);
		List<UserAccount> list = userAccountMng.getListUserAccountByUserId(id);
		if(!CollectionUtils.isEmpty(list)){
			model.addAttribute("user_account_id",list.get(0).getId());
		}
		return "user/to_edit_user";
	}
	@RequestMapping("/user/v_toViewUser.do")
	public String toViewUser(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		List<UserAccount> list = userAccountMng.getListUserAccountByUserId(id);
		if(!CollectionUtils.isEmpty(list)){
			model.addAttribute("user_account_id",list.get(0).getId());
		}
		model.addAttribute("user_id",id);
		return "user/to_view_user";
	}
	@RequestMapping("/user/v_edit.do")
	public String edit(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserInfo user = manager.findById(id);
		
		List<ShopInfo> shopList = shopInfoMng.getAll(CmsUtils.getUser(request));
		List<UserInfo> carAdvisers = manager.getAll(CmsUtils.getUser(request));
		UserInfo temp = new UserInfo();
		temp.setId(0);
		temp.setName("请选择");
		carAdvisers.add(0, temp);
		model.addAttribute("user",user);
		model.addAttribute("shopList",shopList);
		model.addAttribute("carAdvisers",carAdvisers);
		return "user/edit_user";
	}
	@RequestMapping("/user/v_toEditAddress.do")
	public String toEditAddress(Integer id, HttpServletRequest request, ModelMap model) {
//		WebErrors errors = validateEdit(id, request);
//		if (errors.hasErrors()) {
//			return errors.showErrorPage(model);
//		}
		Address address = manager.findByIdAddress(id);
		List<ShopInfo> shopList = shopInfoMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("address",address);
		model.addAttribute("shopList",shopList);
		return "user/edit_address_one";
	}
	@RequestMapping("/user/v_view.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserInfo user = manager.findById(id);
		
		List<ShopInfo> shopList = shopInfoMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("user",user);
		model.addAttribute("shopList",shopList);
		return "user/view_user";
	}
	@RequestMapping("/user/v_edit_address.do")
	public String editAddress(Integer userId, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(userId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserInfo user = manager.findById(userId);
		List<Address> listAddress = manager.getListAddressByUserId(userId);
		if(listAddress!=null){
			for(Address a: listAddress){
				a.setShop(user.getShop());
				a.setUser(user);
			}
		}
		model.addAttribute("listAddress",listAddress);
		model.addAttribute("user",user);
		return "user/edit_address";
	}
	@RequestMapping("/user/v_view_address.do")
	public String viewAddress(Integer userId, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(userId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserInfo user = manager.findById(userId);
		List<Address> listAddress = manager.getListAddressByUserId(userId);
		if(listAddress!=null){
			for(Address a: listAddress){
				a.setShop(user.getShop());
				a.setUser(user);
			}
		}
		model.addAttribute("listAddress",listAddress);
		model.addAttribute("user",user);
		return "user/view_address";
	}
	@RequestMapping("/user/o_save.do")
	public String save(UserInfo bean, Integer shopId,Integer carAdviserId, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		//carAdviserId=0表示“请选择”
		if (null == carAdviserId || carAdviserId.intValue() == 0) {
			carAdviserId = null;
		}
		bean = manager.save(bean,shopId,carAdviserId);
		log.info("save UserInfo id={}", bean.getId());
		cmsLogMng.operating(request, "UserInfo.log.save",  "id=" + bean.getId());
		return "redirect:v_list.do";
	}
	@RequestMapping("/user/o_update.do")
	public String update(UserInfo bean,Integer shopId,Integer carAdviserId,Integer pageNo,HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		
		if((StringUtils.isNotEmpty(bean.getSchool()) && StringUtils.isEmpty(bean.getClasses()))
				|| (StringUtils.isEmpty(bean.getSchool()) && StringUtils.isNotEmpty(bean.getClasses()))){
			model.addAttribute("message", "学校名称和班级名称必须同时填写");
			return edit(bean.getId(), request, model);
		}
		
		SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);

		bean.setUpdateTime(t);
		
		if (null == carAdviserId || carAdviserId.intValue() == 0) {
			carAdviserId = null;
		}
		bean=manager.update(bean,shopId,carAdviserId);
		model.addAttribute("message", "global.success");
		log.info("update UserInfo success. id={}", bean.getId());
		cmsLogMng.operating(request, "UserInfo.log.update",  "id=" + bean.getId());
		return edit(bean.getId(), request, model);
	}
	@RequestMapping("/user/o_updateAddress.do")
	public String updateAddress(Integer userId,Integer [] id,String[] consigneeName,String[] consigneeAddr,Long [] mobile,String [] email,
			Integer[]isDefault
			,Integer pageNo,HttpServletRequest request,ModelMap model) {
//		WebErrors errors = validateUpdateForProductRelation(bean.getId(), request);
//		if (errors.hasErrors()) {
//			return errors.showErrorPage(model);
//		}
		UserInfo user=manager.findById(userId);
		List<Address> listAddress = getListAddress(user, id, consigneeName, consigneeAddr, mobile, email, isDefault);
		manager.updateAddressList(listAddress, userId);
		model.addAttribute("message", "global.success");
		return editAddress(userId, request, model);
	}
	@RequestMapping("/user/o_updateAddress_one.do")
	public String updateAddress_one(Address bean,Integer shopId,Integer pageNo,HttpServletRequest request,ModelMap model) {
//		WebErrors errors = validateUpdateForProductRelation(bean.getId(), request);
//		if (errors.hasErrors()) {
//			return errors.showErrorPage(model);
//		}
		SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);

		bean.setUpdateTime(t);
		ShopInfo shop=shopInfoMng.findById(shopId);
		bean.setShop(shop);
		bean=manager.updateAddress(bean, shopId);
		model.addAttribute("message", "global.success");
		log.info("update Address success. id={}", bean.getId());
		cmsLogMng.operating(request, "Address.log.update",  "id=" + bean.getId());
		return toEditAddress(bean.getId(), request, model);
	}
	
	public List<Address> getListAddress(UserInfo user,Integer [] id,String[] consigneeName,String[] consigneeAddr,Long [] mobile,String [] email,
			Integer[]isDefault){
		List <Address> list=new ArrayList<Address>();
		Address ps ;
		 for(int i=0 ;i< consigneeName.length;i++ ){
			  ps = new Address();
			 if(id!=null&&id[i]!=null){
				 ps.setId(id[i]);
			 }
			 ps.setConsigneeName(consigneeName[i]);
			 ps.setConsigneeAddr(consigneeAddr[i]);
			 ps.setMobile(mobile[i]);
			 ps.setEmail(email[i]);
			 ps.setIsDefault(isDefault[i]);
			 ps.setUser(user);
			 ps.setShop(user.getShop());
			 list.add(ps);
		 }
		return list;
	}
	@RequestMapping("/user/o_delete.do")
	public String delete(Integer[] ids, Integer shopId,String mobile,String name,Short status,Integer carAdviserId,Date q_createTime_start,
			Date q_createTime_end,Integer pageNo, HttpServletRequest request,	ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserInfo[] beans = manager.deleteByIds(ids);
		for (UserInfo bean : beans) {
			log.info("delete UserInfo id={}", bean.getId());
			cmsLogMng.operating(request, "UserInfo.log.delete", "id="
					+ bean.getId() + ";name=" + bean.getName());
		}
		return list(shopId,mobile,name,status, carAdviserId,q_createTime_start,q_createTime_end,pageNo, request, model);
	}
	@RequestMapping("/user/o_deleteAddress.do")
	public String deleteAddress(Integer[] ids, String userName,Integer shopId,String consigneeName,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Address[] beans = manager.deleteByIdsAddress(ids);
		for (Address bean : beans) {
			log.info("delete Address id={}", bean.getId());
			cmsLogMng.operating(request, "Address.log.delete", "id="
					+ bean.getId() + ";name=" + bean.getConsigneeName());
		}
		return listAddress(userName, shopId, consigneeName, pageNo, request, model);
	}
	
	@RequestMapping("/user/o_resetPwd.do")
	public String resetPwd(Integer id, Integer shopId,String name,Short status,Integer carAdviserId,Date q_createTime_start,
			Date q_createTime_end,Integer pageNo, HttpServletRequest request,	ModelMap model) {
		WebErrors errors =  WebErrors.create(request);
		vldExist(id, errors);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserInfo bean = manager.resetPwd(id);
		if(bean == null){
			model.addAttribute("message", "global.failed");
		}else{
			model.addAttribute("message", "global.success");
		}
		return list(shopId,null,name,status, carAdviserId,q_createTime_start,q_createTime_end,pageNo, request, model);
	}
	
	
	/**
	 * 审核通过
	 * @param ids
	 * @param shopId
	 * @param mobile
	 * @param name
	 * @param status
	 * @param carAdviserId
	 * @param q_createTime_start
	 * @param q_createTime_end
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/user/o_audit.do")
	public String audit(String[] ids, Integer shopId,String mobile,String name,Short status,Integer carAdviserId,Date q_createTime_start,
			Date q_createTime_end,Integer pageNo, HttpServletRequest request,	ModelMap model) {
		WebErrors errors = WebErrors.create(request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		
		for (String id : ids) {
			UserInfo entity = manager.findById(Integer.valueOf(id));
			if (entity != null) {
				entity.setStatus(status);
				manager.update(entity, entity.getShop().getId(), null);
			}
		}
		
		return list(shopId,mobile,name,status, carAdviserId,q_createTime_start,q_createTime_end,pageNo, request, model);
	}
	
	
	private WebErrors validateSave(UserInfo bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}
	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		UserInfo entity = manager.findById(id);
		if (errors.ifNotExist(entity, UserInfo.class, id)) {
			return true;
		}
		return false;
	}
	
	
	@RequestMapping("/user/v_checkcode_list.do")
	public String listCheckCode(String school,String classes,String checkCode,Integer pageNo,HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPageCheckCode(school, classes, checkCode, cpn(pageNo),CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("school",school);
		model.addAttribute("classes",classes);
		model.addAttribute("checkCode",checkCode);
		return "user/list_checkcode";
	}
	
	@RequestMapping("/user/v_toadd_checkcode.do")
	public String toAddCheckCode(HttpServletRequest request, ModelMap model) {
		
		CheckCode code = new CheckCode();
		
		model.addAttribute("checkcode",code);
		return "user/add_checkcode";
	}
	
	@RequestMapping("/user/v_add_checkcode.do")
	public String addCheckCode(CheckCode code, HttpServletRequest request, ModelMap model) {
	
		manager.saveCheckCode(code);
		
		return listCheckCode(code.getSchool(), code.getClasses(), code.getCheckCode(), 1, request, model);
	}
	
	
	@RequestMapping("/user/v_toEdit_checkcode.do")
	public String toEditCheckCode(Integer id, HttpServletRequest request, ModelMap model) {
		
		CheckCode code = manager.getCheckCodeById(id);
		
		model.addAttribute("checkcode",code);
		return "user/edit_checkcode";
	}
	
	@RequestMapping("/user/v_edit_checkcode.do")
	public String editCheckCode(CheckCode code, HttpServletRequest request, ModelMap model) {
	
		manager.updateCheckCode(code);
		
		return listCheckCode(code.getSchool(), code.getClasses(), code.getCheckCode(), 1, request, model);
	}
	
	@RequestMapping("/user/v_del_checkcode.do")
	public String delCheckCode(Integer id, HttpServletRequest request, ModelMap model) {
		manager.deleteCheckCode(id);
		return listCheckCode(null, null, null, 1, request, model);
	}
	
	
	@Autowired
	private UserInfoMng manager;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private DictionaryMng DicMng;
	@Autowired
	private WiShopInfoMng shopInfoMng;
	@Autowired
	private CarAdviserMng carAdviserMng;
	
	@Autowired
	private UserAccountMng userAccountMng;
}
